07. Return Values

Returning vs. Logging

Returning vs. Logging

It’s important to understand that return and print are not the same thing. Printing a value to the JavaScript console only displays a value (that you can view for debugging purposes), but the value it displays can't really be used for anything more than that. For this reason, you should remember to only use console.log to test your code in the JavaScript console.

Paste the following function declaration and function invocation into the JavaScript console to see the difference between logging (printing) and returning:

function isThisWorking(input) {
  console.log("Printing: isThisWorking was called and " + input + " was passed in as an argument.");
  return "Returning: I am returning this string!";
}

isThisWorking(3);

Prints: "Printing: isThisWorking was called and 3 was passed in as an argument"

Returns: "Returning: I am returning this string!"

If you don't explicitly define a return value, the function will return undefined by default.

function isThisWorking(input) {
  console.log("Printing: isThisWorking was called and " + input + " was passed in as an argument.");
}

isThisWorking(3);

Prints: "Printing: isThisWorking was called and 3 was passed in as an argument"

Returns: undefined

Return vs. Print

What does this function "return"?

function sleep() {
  console.log("I'm sleepy!");
  return "zzz";
  return "snore";
}

sleep();
SOLUTION: "zzz"

Multiple Returns

What number will be "printed" (to the JavaScript console)?

function square(x) {
  return x * x;
}

function subtractFour(x) {
  return square(x) - 4;
}

console.log(subtractFour(5));
SOLUTION: 21

What Returns First?

What do you think will happen with the following code?

function test() {
  return 1;
  return 2;
}

test();
SOLUTION: `1` will be returned